﻿using System;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace ArchitectingInnovation.PRISMvvM.Core.Extensions
{
    public class EventToCommandConverter
    {
        public string CommandName { get; set; }

        public string EventName { get; set; }

        public ICommand Command { get; private set; }

        public void Bind(object dataContext, FrameworkElement elt)
        {
            Command = dataContext.GetType().GetProperty(CommandName) as ICommand;
            if (Command == null)
                return;
            EventHandler dummyDelegate = (s, e) => Execute(e);
            var eventInfo = elt.GetType().GetEvent(EventName);
            var handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, dummyDelegate.Target, dummyDelegate.Method);
            eventInfo.AddEventHandler(elt, handler);
        }

        private void Execute(object parameter)
        {
            this.Command.Execute(parameter);
        }
    }
}
